package com.tn.wservice.validator;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.tn.wservice.validator.IValidationResult.Result;

public class AtleastNNotNullValidator implements IValidator {

	private List<AtleastNValidationImpl> validations = new ArrayList<AtleastNValidationImpl>();

	@Override
	public IValidationResult validate(Object businessObject) throws Exception {
		ValidationResultImp resultImp = new ValidationResultImp();
		Class<? extends Object> clazz = businessObject.getClass();

		for (AtleastNValidationImpl validation : this.getValidations()) {
			int counter = 0;
			int expectedNotNulls = validation.getExpectedNotNull();
			List<String> getterMethods = validation.getGetterMethods();
			for (String methodName : getterMethods) {
				Method method = clazz.getMethod(methodName);
				Object result = method.invoke(businessObject);
				if (null != result) {
					counter++;
				}
			}
			if (counter < expectedNotNulls) {
				resultImp.setResult(Result.FAILURE);
				resultImp.addErrorMsg(validation.getErrorMsg());
			}
		}
		return resultImp;
	}

	public void setValidations(List<AtleastNValidationImpl> validations) {
		this.validations = validations;
	}

	public List<AtleastNValidationImpl> getValidations() {
		return validations;
	}

}
